<template>
  <div class="article-page">
    <van-nav-bar fixed placeholder>
      <template #left>
        <van-tabs
          v-model="active"
          color="#000"
          title-inactive-color="#aaa"
          line-width="12px"
        >
          <van-tab title="推荐"></van-tab>
          <van-tab title="最新"></van-tab>
        </van-tabs>
      </template>
      <template #right>
        <div class="logo">
          <img src="@/assets/logo.png" alt="" />
        </div>
      </template>
    </van-nav-bar>

    <!-- 2.  显示没有更多数据的文字 -->
    <van-list
      finished-text="没有更多数据了"
      v-model="loading"
      @load="onLoad"
      :finished="total === list.length"
    >
      <article-item v-for="item in list" :key="item.id" :item="item" />
    </van-list>
  </div>
</template>

<script>
import { getArticlesAPI } from "@/api/article";
import ArticleItem from "@/components/ArticleItem.vue";
export default {
  components: { ArticleItem },
  data() {
    return {
      active: 0,
      list: [],
      loading: false,
      total: 1,
      current: 1,
    };
  },
  methods: {
    async onLoad() {
      const { data } = await getArticlesAPI({
        current: this.current,
        // ! 🐛🐛 fix bug
        // ❌ sorter: !this.active ? null : "weight_desc",
        sorter: this.active ? null : "weight_desc",
      });
      this.current++;
      this.loading = false;
      this.total = data.total;

      this.list.push(...data.rows);
    },
  },
  // 3. watch监听active的变化
  watch: {
    active() {
      // 4. 先清空旧数据
      this.list = [];
      this.current = 1;
      this.total = 1;
      // 💥 阻止第一次就自动请求
      this.loading = true;
      this.onLoad();
    },
  },
};
</script>

<style lang="less" scoped>
.article-page {
  // height: calc(100vh - 65px);

  .logo {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    > img {
      width: 64px;
      height: 28px;
      display: block;
      margin-right: 10px;
    }
  }
}
</style>
